import * as usersService from '../services/users';

export default {
  namespace: 'users',
  state: {
    list: [],
    total: null,
    page: null,
    showModal: false,
    record: {},
    optionDatas: {}
  },  
  reducers: {
    save(state, { payload: { data: list, total, page } }) {
      return { ...state, list, total, page };
    },
    saveOrganization(state, { payload: { data: list} }) {
      let optionDatas = { ...state.optionDatas, ...{ organizations: list } }
      return { ...state, optionDatas };
    },
    savePosition(state, { payload: { data: list} }) {
      let optionDatas = { ...state.optionDatas, ...{ positions: list } }
      return { ...state, optionDatas };
    },
    saveSerial(state, { payload: { data: list} }) {
      let optionDatas = { ...state.optionDatas, ...{ serials: list } }
      return { ...state, optionDatas };
    },
    openModal(state, {payload: {index}}) {
      let record={}
      if (index>=0){
        record=state.list[index]
      }
      const showModal=true;
      return { ...state, showModal, record};
    },
    hideModal(state) {
      const showModal=false;
      return { ...state, showModal};
    }
  },
  effects: {
    *fetch({ payload: { page = 1, sorter, filters} }, { call, put }) {
      const listData = yield call(usersService.fetch, { page, sorter, filters });
      if (listData) {
        yield put({
          type: 'save',
          payload: {
            data: listData.Objectlist,
            total: listData.Count,
            page: parseInt(page, 10),
          },
        });
      }
    },
    *fetchOptions(_, { call, put }) {
      const oData = yield call(usersService.fetchOrganization);
      if (oData) {
        yield put({
          type: 'saveOrganization',
          payload: {
            data: oData
          },
        });
      }
      const pData = yield call(usersService.fetchPosition);
      if (pData) {
        yield put({
          type: 'savePosition',
          payload: {
            data: pData
          },
        });
      }
      const sData = yield call(usersService.fetchSerial);
      if (sData) {
        yield put({
          type: 'saveSerial',
          payload: {  
            data: sData
          },
        });
      }
    },
    *remove({ payload: ids}, { call, put }) {
      yield call(usersService.remove, ids);
      yield put({ type: 'reload' });
    },
    *patch({ payload:  values }, { call, put }) {
      yield call(usersService.patch, values);
      yield put({ type: 'reload' });
    },
    *create({ payload: values }, { call, put }) {
      yield call(usersService.create, values);
      yield put({ type: 'reload' });
    },
    *reload(action, { put, select }) {
      const page = yield select(state => state.users.page);
      yield put({ type: 'fetch', payload: { page } });
    },
  },
};
